import React from 'react'
import { connect } from 'mirrorx'
import Banner from './banner'
import Introduction from './introduction'
import Liability from './liability'
import Claim from './claim'
import Faq from './faq'
import BottomFix from '../../../component/module/BottomFix'
import Title from '../../../component/title'
import { Flex } from 'antd-mobile'
import cuid from 'cuid'
import TrailDom from './trialDom'
import { API } from '../../api'

class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      show: false,
      planInfo: [],
      activePlanId: 1,
      activePlanName: '',
      activePlan: {},
      activeQuestion: 0,
      showAnswer: true,
      amount: 0,
      contentActiveId: 0,
      tabClass: 'tabbar-box',
      titleClass: [],
      planTabList: [],
      diyColor: '#1854C0'
    }
    this.isScrollTop = true
  }

  componentDidMount () {
    this.requestPlanInfo()
  }

  componentWillUnmount () {
    this.close()
  }

  windowOnScroll () { // 滑动置顶
    let _this = this
    let isScrollTop = _this.isScrollTop
    let elem = T.get('tabbar')
    let offsetTop = T.getOffset(elem).top
    window.onscroll = function () {
      // 获取滚动条滚动的距离
      let scrollTop = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0
      if (scrollTop >= offsetTop) {
        if (isScrollTop) {
          isScrollTop = false
          _this.setState({
            tabClass: 'tabbar-box tabbar-box-fixed'
          })
        }
      } else {
        if (!isScrollTop) {
          isScrollTop = true
          _this.setState({
            tabClass: 'tabbar-box'
          })
        }
      }
    }
  }

  requestPlanInfo () {
    T.fetch2({
      url: API.queryGoodsDetail.path,
      data: { channelGoodsId: T.urlQuery('channelGoodsId') },
      loading: true
    }).then((res) => {
      if (res.success) {
        let selectPlanList = [] // 多计划数据处理
        let planTabList = []
        let diycolor = '#00B34A'
        if (res.value) {
          // if (res.value.templateCode == 1) {
          //   diycolor = '#00B34A'
          // } else {
          //   diycolor = '#00B34A'
          // }
          let chPlanList = res.value.channelGoodsPlanDTOList
          let planItem

          if (chPlanList) {
            for (var i = 0; i < chPlanList.length; i++) {
              planItem = chPlanList[i]

              selectPlanList.push({
                channelPlanId: planItem.channelGoodsPlanId,
                channelPlanName: planItem.channelGoodsPlanName,
                liabilityList: planItem.liabilityDTOList || []
              }
              )
              planTabList.push({ id: planItem.channelGoodsPlanId, title: planItem.channelGoodsPlanName })
            }
          }
        }
        // 給默認值
        const PlanModel = planTabList[0] || {}
        this.setState({
          planInfo: res.value,
          selectPlanList: selectPlanList,
          planTabList: planTabList,
          activePlanId: PlanModel.id,
          activePlanName: PlanModel.title,
          diyColor: diycolor
        }, () => {
          this.windowOnScroll()
          T.setColor(diycolor)
        })
      }
    })
  }

  sort (arr, key) { // 排序 从小到大 arr是需要排序的对象数组  key是排序的关键字比如orderNo
    var len = arr.length
    for (var i = 0; i < len; i++) {
      for (var j = 0; j < len - 1 - i; j++) {
        if (arr[j][key] > arr[j + 1][key]) {
          var temp = arr[j + 1]
          arr[j + 1] = arr[j]
          arr[j] = temp
        }
      }
    }
    return arr
  }

  clickPlan (planId, plan) {
    this.setState({ activePlanId: planId, activePlanName: plan.title })
  }

  clickFaq (index) {
    this.setState({ activeQuestion: index })
  }

  clickBtn () { // 點擊确认
    T.sessionStorage.set('price', this.state.amount)
    this.toInformOrInsure()
  }
  toInformOrInsure () {
    global.location.href = `/insure-yj-en?planId=${this.state.activePlanId}&planName=${this.state.activePlanName}&channelGoodsId=${T.urlQuery('channelGoodsId')}&goodsId=${T.urlQuery('goodsId')}&productName=${T.urlQuery('productName')}&cuid=${cuid()}`
  }

  close () {
    this.setState({
      show: false
    })
  }

  clickTab (index) { // 點擊頂部商品詳情 理賠流程等tab
    let titleClass = ['', '', '']
    titleClass[index] = 'pt80'
    this.setState({ contentActiveId: index })
    setTimeout(function () {
      global.location.replace('#' + index)
    }, 100)
  }

  getAmount (a) {
    this.setState({
      amount: a
    })
  }

  showTrial () {
    this.setState({
      show: true
    })
  }

  render () {
    const { show, planInfo, activePlanId, diyColor, tabClass, planTabList, contentActiveId, selectPlanList, activeQuestion, showAnswer, amount } = this.state
    const tabList = [window.LangMessage.product_detail || '商品详情', window.LangMessage.claim_process || '理赔流程', window.LangMessage.FAQ || '常见问题']
    let imgs = planInfo.channelGoodsMediaDTOList || [] // 1-主图 2-商品小图 3-商品详情图 4-理赔图 5-附加图
    let featureFileCode = (T.getAttrObject(imgs, 'mediaCategory', 1)[0] || {}).fileCode
    let claimCode = (T.getAttrObject(imgs, 'mediaCategory', 4)[0] || {}).fileCode
    console.log(claimCode||'')
    console.log(claimCode||[])
    let introduceCode = (T.getAttrObject(imgs, 'mediaCategory', 3)[0] || {}).fileCode

    return (<div className='product-detail-yj clearfix'>
      <div className='wrap clearfix'>
        <Banner
          mainCoverFileCode={featureFileCode}
        />
        <Liability
          clickPlan={this.clickPlan.bind(this)}
          activePlanId={activePlanId}
          amount={amount}
          selectPlanList={selectPlanList}
          planTabList={planTabList}
          diyColor={diyColor}
        />
        <div className={tabClass} id='tabbar'>
          <ul className='tabbar fc3'>
            {tabList && tabList.map((item, index) =>
              <li key={index} className={contentActiveId === index ? 'diy_color diy_border_bottom-yj' : ''} onClick={() => this.clickTab(index)}>
                {item}</li>
            )}
          </ul>
        </div>
        <div id='0'>
          <Title title={window.LangMessage.product_detail || '商品详情'} />
        </div>
        <Introduction
          featureFileCode={introduceCode || ''}
        />
        <div id='1'>
          <Title title={window.LangMessage.claim_process || '理赔流程'} />
        </div>
        <Claim
          claimCode={claimCode||''}
        />
        <div id='2'>
          <Title title={window.LangMessage.FAQ || '常见问题'} />
        </div>
        <Faq
          faqList={planInfo.channelGoodsFaqDTOList || []}
          clickFaq={this.clickFaq.bind(this)}
          activeQuestion={activeQuestion}
          showAnswer={showAnswer}
        />
      </div>

      <div>
        {show &&
          <div>
            <div className='layer-mask' onClick={this.close.bind(this)} />
            <div className='trial bgfw w-750'>
              <Flex className='item pl30 pr30 bor-top' style={{ lineHeight: '1rem' }}>
                <Flex.Item className='fc48 tal f32'>{window.LangMessage.trial || '保険料お見積もり' || '试算'}</Flex.Item>
                <Flex.Item className='fc48 tar f48' onClick={this.close.bind(this)}>×</Flex.Item>
              </Flex>
              <TrailDom id={activePlanId} getAmount={this.getAmount.bind(this)} />
              <BottomFix clickBtn={this.clickBtn.bind(this)} amount={amount} />
            </div>
          </div>
        }
      </div>
      <div style={{ height: '1rem' }} />
      <div className='trialBtn g-bottomFix diy_background fcw tac f30' onClick={this.showTrial.bind(this)} >{window.LangMessage.trial || '保険料お見積もり' || '试算'}</div>

    </div>)
  }
}
let Capp = App
if (global.window) {
  Capp = connect(state => {
    return state.mainModel
  })(App)
}

export default Capp
